package cn.kooki.app.duobao.ui.widget;

import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.text.Editable;
import android.text.Selection;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import cn.kooki.app.duobao.R;
import cn.kooki.app.duobao.util.StringUtils;

/**
 * Created by xiong on 2015/12/12.
 */
public class NumberPicker extends RelativeLayout implements View.OnClickListener {

    private EditText input;
    private ImageButton minus;
    private ImageButton plus;
    private int onceCount = 1;
    private int maxCount = -1;
    private int currtCount;

    private OnNumberValueChangerListener changerListener;

    public interface OnNumberValueChangerListener {
        void onChanged(int value);
    }

    public void setChangerListener(OnNumberValueChangerListener changerListener) {
        this.changerListener = changerListener;
    }

    public void setCurrtCount(int currtCount) {
        this.currtCount = currtCount;
        input.setText(currtCount + "");
        if (maxCount != -1 && currtCount >= maxCount) {
            plus.setEnabled(false);
        } else {
            plus.setEnabled(true);
        }
    }

    public int getCurrtCount() {
        return StringUtils.nullSafeParseInt(input.getText().toString());
    }

    public void setMaxCount(int maxCount) {
        this.maxCount = maxCount;
    }

    public void setOnceCount(int onceCount) {
        this.onceCount = onceCount;
    }

    public NumberPicker(Context context) {
        this(context, null);
    }

    public NumberPicker(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public NumberPicker(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }


    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public NumberPicker(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init();
    }

    private NumPickTextWather textWather;

    private void init() {
        textWather = new NumPickTextWather();
        LayoutInflater.from(getContext()).inflate(R.layout.layout_numberpicker, this, true);
        input = (EditText) findViewById(R.id.input);
        minus = (ImageButton) findViewById(R.id.minus);
        plus = (ImageButton) findViewById(R.id.plus);
        minus.setOnClickListener(this);
        plus.setOnClickListener(this);

        input.setOnFocusChangeListener(new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                System.out.println(hasFocus);
                int number = updatenumber();
                input.setText(number + "");
            }
        });
        input.addTextChangedListener(textWather);
        input.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_FLAG_NO_ENTER_ACTION) {
                    hideSoftKeyBoard();
                    int number = updatenumber();
                    input.setText(number + "");
                }
                return true;
            }
        });

    }


    public class NumPickTextWather implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            int number = updatenumber();
            input.removeTextChangedListener(this);
            String lable = number + "";
            input.setText(lable);
            input.setSelection(lable.length());
            input.addTextChangedListener(this);
            if (changerListener != null) {
                changerListener.onChanged(number);
            }
        }
    }


    public void hideSoftKeyBoard() {
        InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(input.getWindowToken(), 0);

    }

    private int updatenumber() {
        int number = StringUtils.nullSafeParseInt(input.getText().toString());
        if (onceCount == 0) {
            onceCount = 1;
        }
        number = (number / onceCount) * onceCount;
        if (maxCount != -1 && maxCount <= number) {
            number = maxCount;
            minus.setEnabled(true);
            plus.setEnabled(false);
        } else if (number <= onceCount) {
            number = onceCount;
            minus.setEnabled(false);
            plus.setEnabled(true);
        }
        return number;
    }

    @Override
    public void onClick(View v) {
        if (v == minus) {
            changeCount(false);
        }
        if (v == plus) {
            changeCount(true);
        }
    }

    public void changeCount(boolean isplus) {
        String inputstring = input.getText().toString();
        int number = StringUtils.nullSafeParseInt(inputstring);
        if (isplus) {
            number += onceCount;
            minus.setEnabled(true);
            if (maxCount != -1 && number >= maxCount) {
                number = maxCount;
                plus.setEnabled(false);
            }
        } else {
            number -= onceCount;
            plus.setEnabled(true);
            if (number <= onceCount) {
                number = onceCount;
                minus.setEnabled(false);
            }
        }
        input.setText(number + "");
    }
}
